import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JPanel;
/**
 * reprezinta clasa Proxy din sablon avand o referinta catre 
 * subiectul real constituit din imagine.
 * 
 */
public class ImageProxy extends JPanel implements Runnable 
{
	private int height, width;
	private MediaTracker tracker;
	private Image img;
	private JFrame frame;
	private Thread imageCheck; //to monitor loading

	/**
	 *  
	 * @param filename
	 * @param w
	 * @param h
	 * constructorul clasei se ocupa de incarcarea imaginii
	 */
	public ImageProxy(String filename, int w, int h) {
		height = h;
		width = w;
		tracker = new MediaTracker(this);
		img = Toolkit.getDefaultToolkit().getImage(filename);
		tracker.addImage(img, 0); //watch for image loading
		imageCheck = new Thread(this);
		imageCheck.start(); //start 2nd thread monitor
		//this begins actual image loading
		try {
			tracker.waitForID(0,1);
		} catch (InterruptedException e) {
		}
	}
	
	
	/*this thread monitors image loading
	and repaints when done
	the 1000 millisecond is artificially long
	to allow the demo to display with a delay*/
	/**
	 * acest fir de executie monitorizeaza incarcarea imaginii si apeleaza
	 * functia repaint() la terminare.
	 * exista o intarziere de 1000 de milisecunde pentru a afisa cu intarziere
	 */

	public void run() {
		
		try {
			Thread.sleep(1000);
			while (! tracker.checkID(0))
				Thread.sleep(1000);
		} catch (Exception e) {
		}
		repaint();
	}

/**
 *  functia paint se ocupa de desenarea imaginii
 */
	public void paint(Graphics g) {
		if (tracker.checkID(0)) {
			height = img.getHeight(frame);//get height
			width = img.getWidth(frame); //and width
			//getSetColor(Color.lightGray); //erase box
			g.fillRect(0,0, width, height);
			g.drawImage(img, 0, 0, this); //draw image
		} else {
			//draw box outlining image if not loaded yet
			g.setColor(Color.black);
			g.drawRect(1, 1, width-2, height-2);
		}
	}



}